package org.example.springgobang.game;

import org.example.springgobang.model.Room;
import org.example.springgobang.model.User;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 对战房间管理器
 */
@Component
public class RoomManager {
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    private ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<>();

    public void add(Room room,int userId1,int userId2) {
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }

    public void remove(String roomId,int userId1,int userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room getRoomById(String roomId) {
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(int userId) {
        String tmpRoomId = userIdToRoomId.get(userId);
        if(tmpRoomId == null) {
            return null;
        }
        return rooms.get(tmpRoomId);
    }
}
